//
//  MyOrderListViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/21.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "MyOrderListViewController.h"
#import "MyOrderStateTableViewCell.h"
#import "MyOrderDetailViewController.h"
#import "OrderScoreServiceViewController.h"

static NSString *OrderTableCellID = @"OrderTableCellID";
@interface MyOrderListViewController ()<UITableViewDelegate,UITableViewDataSource,MyOrderStateTableCellDelegate>

@property (nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,assign)NSInteger page;

@end

@implementation MyOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createMainView];
    
}



- (void)createMainView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - 40 - TAB_BAR_HEIGHT) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    [tableView registerClass:[MyOrderStateTableViewCell class] forCellReuseIdentifier:OrderTableCellID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [self loadDataSourceWithIndex:self.viewTag];
    [self createPullFooterRefreshWithIndex:self.viewTag];
    [self createPullHeaderRefreshWithIndex:self.viewTag];
    AutoWeakSelf;
    self.listBlock = ^(NSInteger index) {
        [weakSelf.tableView.mj_header beginRefreshing];
    };
}

- (void)loadDataSourceWithIndex:(NSInteger)index{
    if (self.viewTag != index) {
        self.page = 1;
        [self.dataSource removeAllObjects];
    }
    if (self.page == 1) {
        [self.dataSource removeAllObjects];
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:[NSNumber numberWithInteger:self.page] forKey:@"page"];
    
    //0:已取消 1:待指派  2:待上门  3:等待确认服务  4:待付款  5:已付款
    if (self.viewTag == 0) {
        [dict setObject:@"0,1,2,3,4,5" forKey:@"order_state"];
    }else if (self.viewTag == 6){//取消订单
        [dict setObject:@"0" forKey:@"order_state"];
    }else{
        [dict setObject:[NSNumber numberWithInteger:self.viewTag] forKey:@"order_state"];
    }
    [self showLoading];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kGetMaintailOrders parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        weakSelf.tableView.showEmpty = NO;
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count]){
            if ([responseObject[@"total"] integerValue]<10 || ([responseObject[@"total"] integerValue] == weakSelf.dataSource.count)) {
                [weakSelf.tableView.mj_footer removeFromSuperview];
            }
            [weakSelf.dataSource addObjectsFromArray:[NSArray yy_modelArrayWithClass:[OrderBaseModel class] json:resultData]];
            [weakSelf.tableView reloadData];
            
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count]==0){
            [weakSelf.dataSource removeAllObjects];
            weakSelf.tableView.emptyTitle = @"暂无数据";
            weakSelf.tableView.emptyImg = @"noOrder";
            weakSelf.tableView.showEmpty = YES;
            [weakSelf.tableView reloadData];
        }
    } Failure:^(NSError *error) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}

/**
 取消订单、删除订单
 */
- (void)cancelOrDeleteMaintailOrderActionURL:(NSString *)actionUrl OrderId:(NSString *)order_id{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:order_id?:@"" forKey:@"order_id"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:actionUrl parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] integerValue]) {
                [weakSelf showTipWithTitle:@"操作成功"];
                [weakSelf loadDataSourceWithIndex:self.viewTag];
            }else{
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}


/**
 立即支付
 order_id
 */
- (void)payMaintailOrderWithModel:(NSString *)orderId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:orderId?:@"" forKey:@"order_id"];
    [dict setObject:@"wx" forKey:@"pay_way"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kPayMaintailOrder parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                PayOrderModel *payModel = [PayOrderModel yy_modelWithDictionary:responseObject[@"data"]];
                __block typeof(weakSelf) strongSelf = weakSelf;
                [PayStyleUtil doWxpay:payModel payDone:^(NSString * _Nonnull errorMsg) {
                    if (!errorMsg) {
                        [strongSelf showTipWithTitle:@"支付成功"];
//                        [strongSelf loadDataSourceWithIndex:self.viewTag];
                    }else{
                        [strongSelf showErrorTipWithTitle:errorMsg];
                    }
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter]postNotificationName:kPostNotificationForRepairOrder object:@{@"postIndex":[NSString stringWithFormat:@"%ld",self.viewTag]} userInfo:nil];
                    });
                }];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}


#pragma mark - MyOrderStateTableCellDelegate
//取消订单、查看详情、立即确认、立即支付、立即评价、删除订单
//100、    101、   102、    103、    104、   105、
//取消订单、删除订单
- (void)orderStateCancelButtonIndexPath:(NSIndexPath *)indexPath ActionTag:(NSInteger)actionTag{
    if (indexPath.row >= [self.dataSource count]) {return;}
    OrderBaseModel *model = self.dataSource[indexPath.row];
    switch (actionTag) {
        case 100:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在取消订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kCancelMaintailOrder OrderId:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认取消订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
        }break;
        case 105:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在删除订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kDeleteMaintailOrder OrderId:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        default:
            break;
    }
}


//取消订单、查看详情、立即确认、立即支付、立即评价、删除订单
- (void)orderStateDetailButtonIndexPath:(NSIndexPath *)indexPath ActionTag:(NSInteger)actionTag{
    if (indexPath.row >= [self.dataSource count]) {return;}
    OrderBaseModel *model = self.dataSource[indexPath.row];
    switch (actionTag) {
        case 100:{//取消订单
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在取消订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kCancelMaintailOrder OrderId:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认取消订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
        }break;
        case 101:{//查看详情
            MyOrderDetailViewController *detailVC = [[MyOrderDetailViewController alloc]init];
            detailVC.orderId = model.order_id;
            TAB_PUSH(self, detailVC, YES);
        }break;
        case 102:{//立即确认
            MyOrderDetailViewController *detailVC = [[MyOrderDetailViewController alloc]init];
            detailVC.orderId = model.order_id;
            TAB_PUSH(self, detailVC, YES);
            
//            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [self showTipWithTitle:@"正在确认..."];
//                [self cancelOrDeleteMaintailOrderActionURL:kAcceptMaintailOrder OrderId:model.order_id];
//            }];
//            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            }];
//            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定已知维修报价并需要维修？" preferredStyle:UIAlertControllerStyleAlert];
//            [aleVC addAction:act1];
//            [aleVC addAction:act2];
//            [self presentViewController:aleVC animated:YES completion:nil];
            
            
        }break;
        case 103:{//立即支付
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self payMaintailOrderWithModel:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定已知维修报价并需要维修？" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        case 104:{//立即评价
            OrderScoreServiceViewController *scoreVC = [[OrderScoreServiceViewController alloc]init];
            scoreVC.order_id = model.order_id;
            scoreVC.viewTag = self.viewTag;
            TAB_PUSH(self, scoreVC, YES);
        }break;
        case 105:{//删除订单
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在删除订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kDeleteMaintailOrder OrderId:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
        }break;
        default:
            break;
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyOrderStateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OrderTableCellID];
    cell.delegate = self;
    cell.indexPath = indexPath;
    [cell cellForOrderLayout:self.dataSource[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row >= [self.dataSource count]) {return;}
    OrderBaseModel *model = self.dataSource[indexPath.row];
    MyOrderDetailViewController *detailVC = [[MyOrderDetailViewController alloc]init];
    detailVC.orderId = model.order_id;
    detailVC.viewTag = self.viewTag;
    TAB_PUSH(self, detailVC, YES);
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

#pragma mark - 刷新
- (void)createPullHeaderRefreshWithIndex:(NSInteger)index{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //下拉刷新的block 会被调用
        //清空数组数据
        //下拉刷新的时候是想请求第一页的数据
        self.page = 1;
        //  NSLog(@"上%ld",self.page);
        //请求解析 数据，刷新界面
        [self loadDataSourceWithIndex:index];
        
    }];
}
/**
 *  添加上拉加载
 */
- (void)createPullFooterRefreshWithIndex:(NSInteger)index{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        //请求数据
        // 把数据添加到数组里面
        //上拉加载会调用这个方法
        self.page++;
        // NSLog(@"下%ld",self.page);
        [self loadDataSourceWithIndex:index];
    }];
}

//结束刷新 （)
- (void)endReresh{
    if (self.page == 1) {
        //结束下拉刷新
        [self.tableView.mj_header endRefreshing];
    }else {
        //结束上拉加载
        [self.tableView.mj_footer endRefreshing];
    }
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
